var express = require('express');
var router = express.Router();
var FastScanner = require('fastscan');
const os = require('os');
var moment = require('moment');
let { formateDate, urlf2z, urlf2zList, getPerformer, FormatData } = require('../util.js');
let { isAdminLogin, getUserCount, getUserList, GetUsersById, DeleteUserById, GetAdminList, GetAdminById, getAdminCount,
  UpdateAdminById, DeleteAdminById, addAdmin, getPerformerCount, getPerformerList, GetperformerType, addPerformer, getPerformerById,
  updatePerformerById, DeleteperformerById, getMovieCount, getMovieList, GetmovieById, DeletemovieById, Getmovietag, addmovie, UpdateMovie,
  getmovietagCount, getmovietagList, addmovietag, DeletemovietagById, GetmovietagById, UpdatemovietagById, getCommentCount, getCommentList,
  DeletecommentById, GetuserType, addcomment, GetcommentById, updatecomment, getSensitiveAll, addSensitive, delSensitive, getCommentListAll,
  getUserListWord, getMovietypeTable, getPerformerTable, GetmovieType, Getperformer, getMediaCount, getmediaList, getmediaitiveAll, addMedia,
  deleteMediaById, getMediaById, updateMedia, getnewsList, addNews, GetnewsById,updataNews
} = require('../mysql/index');

let upload = require('../util/multer/index')

router.post('/isAdminLogin', async (req, res, next) => {
  let { username, password, code } = req.body;
  // try {
  //   const sessionCaptcha = req.session.captcha.toLowerCase();
  //   if (sessionCaptcha != code) {
  //     return res.json({
  //       flog: 0,
  //       data: '验证码不正确'
  //     });
  //   }
  // } catch (error) {
  //   return res.json({
  //     flog: 0,
  //     data: '验证码不正确'
  //   });
  // }
  let data = await isAdminLogin({
    username,
    password
  });
  if (!data.length) {
    jsonData = {
      code: 0,
      data: "账号或者密码错误"
    }
  } else {
    jsonData = {
      code: 1,
      data: {
        "access_token": username,
        "name": username,
        "type": "admin",
        "userId": data[0].id
      }
    }
    req.session.AdminInfo = {
      username: username,
      userId: data[0].id,
      url: data[0].url,
      type: "admin"
    }
  }
  return res.json(jsonData)
});

router.get('/adminInfo', async (req, res, next) => {
  if (!req.session.AdminInfo) {
    return res.json({
      code: 500,
      msg: "未登录"
    })
  }
  res.json(
    {
      "code": 200,
      "user": {
        "userId": req.session.AdminInfo.userId,
        "username": req.session.AdminInfo.username,
        "nickName": req.session.AdminInfo.username,
        "url": req.session.AdminInfo.url,
        "type": req.session.AdminInfo.type
      }
    }
  )
});

router.get('/getUserList', async (req, res, next) => {
  let { page, limit, userId, userName, userSex, isusing } = req.query;
  let count = await getUserCount();
  let pageNum = Math.ceil((count / limit));
  if (page > pageNum) {
    return res.json({
      code: 1,
      data: "数据已经加载完毕"
    });
  }
  var num = (page - 1) * limit;
  let data = await getUserList(num, limit, {
    userId, userName, userSex, isusing
  });
  res.json({
    code: 0,
    data: data.data,
    count: data.count
  })
})

router.get('/GetUsersById', async (req, res, next) => {
  let id = req.query.editNo;
  let data = await GetUsersById(id);
  res.json({
    code: 1,
    data
  })
})

router.get('/DeleteUserById', async (req, res, next) => {
  let id = req.query.userId;
  let data = await DeleteUserById(id);
  res.json({
    code: 1,
    data
  })
})

router.post('/UpdateAdminPassById', async (req, res, next) => {
  let { oldPsw, newPsw } = req.body;
  let id = req.session.AdminInfo.userId;
  let username = req.session.AdminInfo.username;
  let admin = await isAdminLogin({
    username,
    password: oldPsw
  });
  if (admin.length) {
    await UpdateAdminById(id, {
      password: newPsw
    })
    return res.json({
      code: 200,
      msg: "修改密码成功"
    })
  } else {
    return res.json({
      code: 500,
      msg: "旧密码错误"
    })
  }

})

router.get('/GetAdminList', async (req, res, next) => {
  let { page, limit, id, name } = req.query;
  let count = await getAdminCount();
  let pageNum = Math.ceil((count / limit));
  if (page > pageNum) {
    return res.json({
      code: 1,
      data: "数据已经加载完毕"
    });
  }
  var num = (page - 1) * limit;
  let data = await GetAdminList(num, limit, {
    id, name
  });
  res.json({
    code: 0,
    data: data.data,
    count: data.count
  })
})

router.get('/GetAdminById', async (req, res, next) => {
  let id = req.query.editNo;
  let data = await GetAdminById(id);
  res.json({
    code: 1,
    data
  })
})

router.post('/UpdateAdminById', upload.single('url'), async (req, res, next) => {
  let { id, name, password, sex, url } = req.body;
  console.log(req.file)
  url = req.file ? urlf2z(`${req.protocol}://${req.headers.host}/${req.file.path}`) : '';
  let data = await UpdateAdminById(id, { name, password, sex, url });
  res.json({
    code: 1,
    data
  })
})

router.post('/DeleteAdminById', async (req, res, next) => {
  let { id } = req.body;
  await DeleteAdminById(id);
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.post('/addAdmin', upload.single('url'), async (req, res, next) => {
  let { name, password, sex, url } = req.body;
  url = req.file ? urlf2z(`${req.protocol}://${req.headers.host}/${req.file.path}`) : '';
  let data = await addAdmin({ name, password, sex, url });
  res.json({
    code: 1,
    data
  })
})

router.get('/getPerformerList', async (req, res, next) => {
  let { page, limit, performerId, performerName } = req.query;
  let count = await getPerformerCount();
  let pageNum = Math.ceil((count / limit));
  if (page > pageNum) {
    return res.json({
      code: 1,
      data: "数据已经加载完毕"
    });
  }
  var num = (page - 1) * limit;
  let data = await getPerformerList(num, limit, {
    performerId, performerName
  });

  res.json({
    code: 0,
    data: data.data,
    count: data.count
  })
})

router.post('/addPerformer', upload.single('performerImg'), async (req, res, next) => {
  let { performerName, performerType, performerContent } = req.body;
  let performerImg = req.file ? urlf2z(`${req.protocol}://${req.headers.host}/${req.file.path}`) : '';
  let data = await addPerformer({ performerName, performerType, performerContent, performerImg })
  res.json({
    code: 1,
    data
  })
})

router.get('/getPerformerById', async (req, res, next) => {
  let { editNo } = req.query;
  let data = await getPerformerById(editNo);
  res.json({
    code: 1,
    data
  })
})

router.get('/GetperformerType', async (req, res, next) => {
  let data = await GetperformerType();
  res.json({
    code: 1,
    data
  })
})

router.post('/updatePerformerById', upload.single('performerImg'), async (req, res, next) => {
  let { performerId, performerName, performerType, performerContent, performerImg } = req.body;
  performerImg = req.file ? urlf2z(`${req.protocol}://${req.headers.host}/${req.file.path}`) : '';
  let data = await updatePerformerById(performerId, { performerName, performerType, performerContent, performerImg });
  res.json({
    code: 1,
    data
  })
})

router.post('/DeleteperformerById', async (req, res, next) => {
  let { performerId } = req.body;
  await DeleteperformerById(performerId);
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.get('/GetmovieList', async (req, res, next) => {
  let { page, limit, movieId, movieName } = req.query;
  let count = await getMovieCount();
  let pageNum = Math.ceil((count / limit));
  if (page > pageNum) {
    return res.json({
      code: 1,
      data: "数据已经加载完毕"
    });
  }
  var num = (page - 1) * limit;
  let data = await getMovieList(num, limit, {
    movieId, movieName
  });
  data.data.forEach(item => {
    item.movieTime = formateDate(item.movieTime)
    item.movieImgList = JSON.parse(item.movieImgList)
    item.movietag = JSON.parse(item.movietag);
  })
  res.json({
    code: 0,
    data: data.data,
    count: data.count
  })
})

router.get('/GetmovieById', async (req, res, next) => {
  let { editNo } = req.query;
  let data = await GetmovieById(editNo);
  let performerList = await getPerformer(JSON.parse(data[0].performerList), getPerformerById);
  data[0].performerList = performerList;
  data[0].movieTime = formateDate(data[0].movieTime)
  data[0].movieImgList = JSON.parse(data[0].movieImgList)
  data[0].movietag = JSON.parse(data[0].movietag);
  res.json({
    code: 1,
    data: data
  })
})

router.post('/DeletemovieById', async (req, res, next) => {
  let { movieId } = req.body;
  await DeletemovieById(movieId);
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.get('/Getmovietag', async (req, res, next) => {
  let data = await Getmovietag();
  res.json({
    code: 1,
    data
  })
})

router.post('/addmovie', upload.array('movieImg', 10), async (req, res, next) => {
  let countFile = req.files.length;
  let { movieName, movieScore, movietag, movieComm, movieType, movieTime, performerList } = req.body;
  if (countFile === 0) {
    return res.json({
      code: 0,
      msg: "至少上传一张图片"
    })
  }
  let movieImgList = urlf2zList(req);
  let movieImg = movieImgList[0];
  movieImgList = JSON.stringify(movieImgList);
  await addmovie({
    movieName, movieScore, movietag, movieComm, movieType, movieTime, performerList,
    movieImg: movieImg,
    movieImgList: movieImgList,
  })
  res.json({
    code: 1,
    data: "添加成功"
  })

})

router.post('/updatamovie', upload.array('movieImg', 10), async (req, res, next) => {
  let { movieId, movieName, movieScore, movietag, movieComm, movieType, movieTime, movieImgList, performerList } = req.body;
  let movieImgListUpdate = urlf2zList(req);
  movieImgList = JSON.parse(movieImgList);
  movieImgList = movieImgList.concat(movieImgListUpdate);
  let movieImg = movieImgList[0];
  movieImgList = JSON.stringify(movieImgList);
  if (!movieImgList.length) {
    return res.json({
      code: 0,
      msg: "至少上传一张图片"
    })
  }
  await UpdateMovie(movieId, {
    movieName, movieScore, movietag, movieComm, movieType, movieTime, movieImg, movieImgList, performerList
  })
  res.json({
    code: 1,
    data: "修改成功"
  })
})

router.get('/GetmovietagList', async (req, res, next) => {
  let { page, limit } = req.query;
  let count = await getmovietagCount();
  let pageNum = Math.ceil((count / limit));
  if (page > pageNum) {
    return res.json({
      code: 1,
      data: "数据已经加载完毕"
    });
  }
  var num = (page - 1) * limit;
  let data = await getmovietagList(num, limit, {});
  res.json({
    code: 0,
    data: data.data,
    count: data.count
  })
})

router.post('/addmovietag', async (req, res, next) => {
  let { movietagName, movietagComm } = req.body;
  let data = await addmovietag({ movietagName, movietagComm })
  res.json({
    code: 1,
    data
  })
})

router.post('/DeletemovieById', async (req, res, next) => {
  let { movieId } = req.body;
  await DeletemovieById(movieId);
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.post('/DeletemovietagById', async (req, res, next) => {
  let { movietagId } = req.body;
  await DeletemovietagById(movietagId);
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.get('/GetmovietagById', async (req, res, next) => {
  let { editNo } = req.query;
  let data = await GetmovietagById(editNo);
  res.json({
    code: 1,
    data: data
  })
})

router.post('/UpdatemovietagById', async (req, res, next) => {
  let { movietagId, movietagName, movietagComm } = req.body;
  let data = await UpdatemovietagById(movietagId, {
    movietagName, movietagComm
  })
  res.json({
    code: 1,
    data: "修改成功"
  })
})

router.get('/GetcommentList', async (req, res, next) => {
  let { page, limit } = req.query;
  let count = await getCommentCount();
  let pageNum = Math.ceil((count / limit));
  if (page > pageNum) {
    return res.json({
      code: 1,
      data: "数据已经加载完毕"
    });
  }
  var num = (page - 1) * limit;
  let data = await getCommentList(num, limit);
  data.data.forEach(item => {
    item.commentTime = formateDate(item.commentTime)
    item.commentImgList = JSON.parse(item.commentImgList)
  })
  res.json({
    code: 0,
    data: data.data,
    count: data.count
  })
})

router.post('/DeletecommentById', async (req, res, next) => {
  let { commentId } = req.body;
  await DeletecommentById(commentId);
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.get('/GetuserType', async (req, res, next) => {
  let data = await GetuserType();
  res.json({
    code: 1,
    data
  })
})

router.post('/addcomment', upload.array('commentImg', 10), async (req, res, next) => {
  let countFile = req.files.length;
  let { commentTitle, userId, commentTime, commentCom, movieId, commentPraise, commentScore } = req.body;
  if (countFile === 0) {
    return res.json({
      code: 0,
      msg: "至少上传一张图片"
    })
  }
  let commentImgList = urlf2zList(req);
  commentImgList = JSON.stringify(commentImgList);
  await addcomment({
    commentTitle, userId, movieId, commentTime, commentCom, commentPraise, commentScore,
    commentImgList: commentImgList
  })
  res.json({
    code: 1,
    data: "添加成功"
  })

})

router.get('/GetmovieType', async (req, res, next) => {
  let data = await GetmovieType();
  res.json({
    code: 1,
    data
  })
})

router.get('/GetcommentById', async (req, res, next) => {
  let { editNo } = req.query;
  let data = await GetcommentById(editNo);
  data[0].commentTime = formateDate(data[0].commentTime)
  data[0].commentImgList = JSON.parse(data[0].commentImgList)
  res.json({
    code: 1,
    data: data
  })
})

router.post('/updatecomment', upload.array('commentImg', 10), async (req, res, next) => {
  let { commentId, commentTitle, userId, commentTime, commentCom, commentPraise, commentImgList, movieId, commentScore } = req.body;
  let commentImgListtUpdate = urlf2zList(req);
  commentImgList = JSON.parse(commentImgList);
  commentImgList = commentImgList.concat(commentImgListtUpdate);
  let movieImg = commentImgList[0];
  commentImgList = JSON.stringify(commentImgList);
  if (!commentImgList.length) {
    return res.json({
      code: 0,
      msg: "至少上传一张图片"
    })
  }
  await updatecomment(commentId, {
    commentTitle, userId, commentTime, commentCom, commentPraise, commentImgList, movieId, commentScore
  })
  res.json({
    code: 1,
    data: "修改成功"
  })
})

router.get('/getSensitiveAll', async (req, res, next) => {
  let data = await getSensitiveAll();
  res.json({
    code: 1,
    data
  })
})

router.post('/addSensitive', async (req, res, next) => {
  let { val } = req.body;
  let info = await addSensitive({
    sensitiveTag: val
  });
  if (!info.affectedRows) {
    return res.json({
      code: 0,
      data: "不能重复添加敏感词"
    })
  } else {
    res.json({
      code: 1,
      data: info
    })
  }
})

router.post('/delSensitive', async (req, res, next) => {
  let { sensitiveId } = req.body;
  await delSensitive(sensitiveId);
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.get('/GetsensitiveCommentList', async (req, res, next) => {
  let { page, limit } = req.query;
  limit = Number(limit);
  var num = (page - 1) * limit;
  let data = await getCommentListAll();
  data.forEach(item => {
    item.commentTime = formateDate(item.commentTime)
    item.commentImgList = JSON.parse(item.commentImgList)
  })
  let sensitiveData = await getSensitiveAll();
  let words = sensitiveData.map((item, index) => {
    return item['sensitiveTag']
  })
  var scanner = new FastScanner(words)
  let info = data.filter(item => {
    var hits = scanner.hits(item.commentCom)
    if (JSON.stringify(hits) !== "{}") {
      item.sensitiveNum = Object.keys(hits);
      return true;
    }
  })
  res.json({
    code: 0,
    data: info.slice(num, num + limit)
  })
})

router.get('/getuserNumTable', async (req, res, next) => {
  let DayList = [];
  for (var i = 1; i <= 7; i++) {
    DayList.push(moment().isoWeekday(i))
  }
  let { count, data } = await getUserListWord();
  let userNum = []
  DayList.forEach(dayItem => {
    let sunNum = 0;
    data.forEach(item => {
      if (dayItem.isSame(item.userTime, 'day')) {
        sunNum++;
      }
    })
    userNum.push(sunNum)
  })

  res.json({
    code: 1,
    userNum: userNum,
    count: count
  })

});

router.get('/getIndexCount', async (req, res, next) => {
  let adminNum = await getAdminCount();
  let movieNum = await getMovieCount();
  let commentNum = await getCommentCount();
  let userNum = await getUserCount();
  res.json({
    code: 1,
    adminNum, movieNum, commentNum, userNum
  })
})

router.get('/getMovietypeTable', async (req, res, next) => {
  let [[{ hotNum }], [{ soonNum }]] = await getMovietypeTable();
  res.json({
    code: 1,
    hotNum, soonNum
  })
})

router.get('/getCpuTable', async (req, res, next) => {
  var freeMem = os.freemem() / 1024 / 1024 / 1024;
  var totalMem = os.totalmem() / 1024 / 1024 / 1024;
  res.json({
    code: 1,
    CpuNum: ((freeMem) / totalMem * 100.0).toFixed(2)
  })
})

router.get('/getPerformerTable', async (req, res, next) => {
  let [[{ performerType }], [{ directorNum }]] = await getPerformerTable();
  res.json({
    code: 1,
    performerType, directorNum
  })
})

router.get('/Getperformer', async (req, res, next) => {
  let data = await Getperformer();
  res.json({
    code: 1,
    data
  })
})

router.get('/getmediaList', async (req, res, next) => {
  let { page, limit } = req.query;
  var num = (page - 1) * limit;
  let data = await getmediaList(num, limit);
  res.json({
    code: 0,
    data: data.data,
    count: data.count
  })
})

router.post('/addMedia', upload.single('mediaAvatar'), async (req, res, next) => {
  let { mediaAuthor } = req.body;
  let mediaAvatar = req.file ? urlf2z(`${req.protocol}://${req.headers.host}/${req.file.path}`) : '';
  let data = await addMedia({ mediaAuthor, mediaAvatar })
  res.json({
    code: 1,
    data
  })
})

router.post('/deleteMediaById', async (req, res, next) => {
  let { mediaId } = req.body;
  await deleteMediaById(mediaId);
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.get('/getMediaById', async (req, res, next) => {
  let { mediaId } = req.query;
  let data = await getMediaById(mediaId);
  res.json({
    code: 1,
    data: data
  })
})

router.post('/updateMedia', upload.single('mediaAvatar'), async (req, res, next) => {
  let { mediaId, mediaAuthor, mediaAvatar } = req.body;
  mediaAvatar = req.file ? urlf2z(`${req.protocol}://${req.headers.host}/${req.file.path}`) : '';
  await updateMedia(mediaId, {
    mediaAuthor, mediaAvatar
  })
  res.json({
    code: 1,
    data: "修改成功"
  })
})

router.get('/GetnewsList', async (req, res, next) => {
  let { page, limit, newsId, newsTitle } = req.query;
  var num = (page - 1) * limit;
  let data = await getnewsList(num, limit, { newsId, newsTitle });
  res.json({
    code: 0,
    data: FormatData(data.data, {
      newsImgSrc: 'json',
      newsTime: 'date'
    }),
    count: data.count
  })
})

router.get('/getmediaitiveAll', async (req, res, next) => {
  let data = await getmediaitiveAll();
  res.json({
    code: 1,
    data
  })
})

router.post('/addNews', upload.array('newsImgSrc', 10), async (req, res, next) => {
  let countFile = req.files.length;
  let { newsTitle, newsContent, mediaId, newsReading, newsCollection, newsTime } = req.body;
  if (countFile === 0) {
    return res.json({
      code: 0,
      msg: "至少上传一张图片"
    })
  }
  let newsImgSrc = urlf2zList(req);
  newsImgSrc = JSON.stringify(newsImgSrc);
  await addNews({
    newsTitle, newsContent, mediaId, newsReading, newsCollection, newsTime, newsImgSrc
  })
  res.json({
    code: 1,
    data: "添加成功"
  })

})

router.get('/GetnewsById', async (req, res, next) => {
  let { newsId } = req.query;
  let data = await GetnewsById(newsId);
  res.json({
    code: 1,
    data: FormatData(data, {
      newsImgSrc: 'json',
      newsTime: 'date'
    })
  })
})

router.post('/DeletenewsById', async (req, res, next) => {
  let { newsId } = req.body;
  await DeletenewsById(newsId);
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.post('/updataNews', upload.array('newsImgSrc', 10), async (req, res, next) => {
  let { newsId, newsTitle, newsContent, mediaId, newsReading, newsCollection, newsTime, newsImgSrcList } = req.body;
  let newsImgListUpdate = urlf2zList(req);
  newsImgSrcList = JSON.parse(newsImgSrcList);
  newsImgSrcList = newsImgSrcList.concat(newsImgListUpdate);
  newsImgSrcList = JSON.stringify(newsImgSrcList);
  if (!newsImgSrcList.length) {
    return res.json({
      code: 0,
      msg: "至少上传一张图片"
    })
  }
  await updataNews(newsId, {
    newsTitle, newsContent, mediaId, newsReading, newsCollection, newsTime, newsImgSrc: newsImgSrcList
  })
  res.json({
    code: 1,
    data: "修改成功"
  })
})

module.exports = router;